from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from ability.models import Knowledge 
from django.conf import settings
from os.path import dirname, isfile, join
from os import listdir

class Command(BaseCommand):
    help = 'import knowledges from point/* '

    def handle(self, *args, **options):
      print('handle import points')
      pointdir = dirname(dirname(dirname(dirname(__file__)))) + "/point"
      onlyfiles = [f for f in listdir(pointdir) if isfile(join(pointdir, f))]
      for f in onlyfiles:
        file = join(pointdir, f)
        rootName = f.replace('.md', '')
        try:
          rootKld, created = Knowledge.objects.get_or_create(knowledge_name=rootName)
          print(rootKld)
          with open(file) as fr:
            gparent = None
            parent = None
            for line in fr:
              line = line.strip()
              if len(line) == 0:
                continue
              try:
                if (line.startswith('## ')):
                  # 重置第三级
                  parent = None
                  gparent = Knowledge()
                  gparent.knowledge_name = line.replace('#', '').strip()
                  gparent.parent = rootKld 
                  gparent.save()
                if (line.startswith('### ')):
                  parent = Knowledge()
                  parent.knowledge_name = line.replace('#','').strip()
                  parent.parent = gparent if gparent !=None else rootKld
                  parent.save()
                  
                if (line.startswith('* ')):
                  obj = Knowledge()
                  obj.knowledge_name = line.replace('*','').strip()
                  obj.parent = parent if parent !=None else gparent if gparent != None else rootKld
                  obj.save()

                if (line.startswith('- ')):
                  obj = Knowledge()
                  obj.knowledge_name = line.replace('-','').strip()
                  obj.parent = parent if parent !=None else gparent if gparent != None else rootKld
                  obj.save()
              except Exception as e:
                print(str(e))
        except Exception as e:
          print(str(e))

